//
//  WisdomLiveHTTPSessionManager.m
//  WisdomLive
//
//  Created by 葛 军 on 2018/5/11.
//  Copyright © 2018年 com.jszhaomi. All rights reserved.
//

#import "WisdomLiveHTTPSessionManager.h"
#import "SVProgressHUD.h"
NSString *const Wisdom_kKeyCode = @"code";
NSString *const kKeyMessage = @"error";
NSString *const KKeyMsg = @"msg";
//解析数据返回错误
NSString *const kParseResponseError = @"解析数据失败";
NSString *const kHttpRequestFailure = @"服务器获取失败";
NSString *const kHttpServerInnerError = @"内部处理错误";
NSString *const KHttpSucessMessage = @"请求成功";
@implementation WisdomLiveHTTPSessionManager

- (instancetype)init{
    self = [super initWithBaseURL:[NSURL URLWithString:BaseUrl]];
    if (self) {
        self.requestSerializer = [AFJSONRequestSerializer serializer];//请求
        self.requestSerializer.HTTPShouldHandleCookies = YES;
        self.requestSerializer.HTTPMethodsEncodingParametersInURI = [NSSet setWithObjects:@"GET", @"HEAD", nil];
        [self.requestSerializer setValue:@"3.9" forHTTPHeaderField:@"Api-Version"];
        self.responseSerializer.acceptableContentTypes =[NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html",nil];
        [self.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        //响应没有设置默认是JSON
        //[[SDWebImageDownloader sharedDownloader] setValue:@"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8" forHTTPHeaderField:@"Accept"];
        //配置https
//        self.securityPolicy.validatesDomainName = NO;
//        self.securityPolicy = [self customSecurityPolicy];
//        [self.securityPolicy setAllowInvalidCertificates:YES];
    }
    return self;
}
#pragma mark- 配置https

- (AFSecurityPolicy *)customSecurityPolicy
{
    /** https */
    if ([self.baseURL isEqual:[NSURL URLWithString:@"https://www.books500.com"]]) {
        NSString*cerPath = [[NSBundle mainBundle] pathForResource:@"www.books500.com.cer"ofType:nil];
        NSData*cerData = [NSData dataWithContentsOfFile:cerPath];
        NSSet*set = [[NSSet alloc] initWithObjects:cerData,nil];
        AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate withPinnedCertificates:set];
        return policy;
    }
    NSString*cerPath = [[NSBundle mainBundle] pathForResource:@"dev.books500.com.cer"ofType:nil];
    NSData*cerData = [NSData dataWithContentsOfFile:cerPath];
    NSSet*set = [[NSSet alloc] initWithObjects:cerData,nil];
    AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate withPinnedCertificates:set];
    return policy;
}


+ (instancetype)manager{
    return [[self alloc] init];
}

- (NSURLSessionDataTask *)POSTWithControllerName:(NSString *)controllerName
                                             url:(NSString *)url
                                      parameters:(id)parameters
                                        complete:(completeBlock)complete{
    [self loadCookies];
    NSString *requestURL = nil;
    if (url == nil || url.length == 0) {
        requestURL = controllerName;
    }else{
        requestURL = [NSString stringWithFormat:@"%@/%@",controllerName, url];
    }
    
    return [super POST:requestURL
            parameters:parameters
              progress:^(NSProgress * _Nonnull uploadProgress) {
                  
              } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                  if ([[NSString stringWithFormat:@"%@",responseObject[@"code"]] isEqualToString:@"200"]) {
                      [self saveCookies];
                      complete(DCHttpResultSuccess,KHttpSucessMessage, responseObject);
                  }else{
                      complete(DCHttpResultFailure, kHttpRequestFailure, responseObject);

                      [self handleNotLoginWithErrorMessage:[NSString stringWithFormat:@"%@",responseObject[@"msg"]]];
                      

                  }
                  
              } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                  NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
                  complete(DCHttpResultFailure, kHttpRequestFailure, response);
                  [self handleNotLoginWithErrorMessage:kHttpRequestFailure];
  
              }];
    
    
}




- (NSURLSessionDataTask *)GETWithControllerName:(NSString *)controllerName
                                            url:(NSString *)url
                                     parameters:(id)parameters
                                       complete:(completeBlock)complete{
    [self loadCookies];
    NSString *requestURL = nil;
    if (![url isKindOfClass:[NSString class]] ||url == nil || url.length == 0) {
        requestURL = controllerName;
    }else{
        requestURL = [NSString stringWithFormat:@"%@/%@",controllerName, url];
    }
    return [super GET:requestURL
           parameters:parameters
             progress:^(NSProgress * _Nonnull uploadProgress) {
                 
             } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                 if ([[NSString stringWithFormat:@"%@",responseObject[@"code"]] isEqualToString:@"200"]) {
                     [self saveCookies];
                     complete(DCHttpResultSuccess,KHttpSucessMessage, responseObject);
                 }else{
                     complete(DCHttpResultFailure, kHttpRequestFailure, responseObject);
                     
                     [self handleNotLoginWithErrorMessage:[NSString stringWithFormat:@"%@",responseObject[@"msg"]]];
                     
                     
                 }
                 
             } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                 NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
                 complete(DCHttpResultFailure, kHttpRequestFailure, response);
                 [self handleNotLoginWithErrorMessage:kHttpRequestFailure];
                 
             }];
}
- (NSURLSessionDataTask *)PUTWithControllerName:(NSString *)controllerName
                                            url:(NSString *)url
                                     parameters:(id)parameters
                                       complete:(completeBlock)complete{
    [self loadCookies];
    
    NSString *requestURL = nil;
    if (url == nil || url.length == 0) {
        requestURL = controllerName;
    }else{
        requestURL = [NSString stringWithFormat:@"%@/%@",controllerName, url];
    }
    return [super PUT:requestURL
           parameters:parameters
              success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([[NSString stringWithFormat:@"%@",responseObject[@"code"]] isEqualToString:@"200"]) {
            [self saveCookies];
            complete(DCHttpResultSuccess,KHttpSucessMessage, responseObject);
        }else{
            complete(DCHttpResultFailure, kHttpRequestFailure, responseObject);
            [self handleNotLoginWithErrorMessage:[NSString stringWithFormat:@"%@",responseObject[@"msg"]]];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
        complete(DCHttpResultFailure, kHttpRequestFailure, response);
        [self handleNotLoginWithErrorMessage:kHttpRequestFailure];
    }];
    
}
- (NSURLSessionDataTask *)DeleteWithControllerName:(NSString *)controllerName
                                               url:(NSString *)url
                                        parameters:(id)parameters
                                          complete:(completeBlock)complete{
    [self loadCookies];
    NSString *requestURL = nil;
    if (url == nil || url.length == 0) {
        requestURL = controllerName;
    }else{
        requestURL = [NSString stringWithFormat:@"%@/%@",controllerName, url];
    }
    
    return [super DELETE:requestURL
              parameters:parameters
                 success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                     if ([[NSString stringWithFormat:@"%@",responseObject[@"code"]] isEqualToString:@"200"]) {
                         [self saveCookies];
                         complete(DCHttpResultSuccess,KHttpSucessMessage, responseObject);
                     }else{
                         complete(DCHttpResultFailure, kHttpRequestFailure, responseObject);
                         [self handleNotLoginWithErrorMessage:[NSString stringWithFormat:@"%@",responseObject[@"msg"]]];
                         
                     }
                     
                 } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                     NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
                     complete(DCHttpResultFailure, kHttpRequestFailure, response);

                    [self handleNotLoginWithErrorMessage:kHttpRequestFailure];
                 }];}


- (nullable NSURLSessionDataTask *)DownloadWithString:(NSString *)urlStr parameters:(id)parameters complete:(completeBlock)complete {
    return [super GET:urlStr parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSData *pdfData = (NSData *)responseObject;
        NSArray *arr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSFileManager *defaultManager = [NSFileManager defaultManager];
        //删除原来的PDF
        [defaultManager removeItemAtPath:[arr[0] stringByAppendingPathComponent:@"PDF.pdf"] error:nil];
        //缓存新的PDF
        [pdfData writeToFile:[arr[0] stringByAppendingPathComponent:@"PDF.pdf"] atomically:YES];
        
        if ([[responseObject valueForKey:Wisdom_kKeyCode] integerValue] ==200) {
            complete(DCHttpResultSuccess, nil, responseObject);
        }else{
            complete(DCHttpResultFailure,[responseObject objectForKey:KKeyMsg], responseObject);
            [self handleNotLoginWithErrorMessage:[NSString stringWithFormat:@"%@",responseObject[@"msg"]]];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
        complete(DCHttpResultFailure, kHttpRequestFailure, response);
        [self handleNotLoginWithErrorMessage:kHttpRequestFailure];
        
    }];
}
- (BOOL)isErrorResponeObjectFormatCorrect:(id)responseObject{
    return [responseObject isKindOfClass:[NSDictionary class]] &&
    [[responseObject allKeys]containsObject:Wisdom_kKeyCode] &&
    [[responseObject allKeys] containsObject:kKeyMessage];
}
- (void)handleNotLoginWithErrorMessage:(NSString *)errorMessage{
    if (errorMessage.length) {
        [SVProgressHUD showInfoWithStatus:errorMessage];
    }
}

-(BOOL)isSucessBack{
    return YES;
}

- (void)saveCookies{
    NSData *cookiesData = [NSKeyedArchiver archivedDataWithRootObject: [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject: cookiesData forKey: @"sessionCookies"];
    [defaults synchronize];
}
- (void)loadCookies{
    NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData: [[NSUserDefaults standardUserDefaults] objectForKey: @"sessionCookies"]];
    NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (NSHTTPCookie *cookie in cookies){
        [cookieStorage setCookie: cookie];
    }
    
}
@end
